package com.jvmoutofmemory.platform.pushutil.dao;

import com.jvmoutofmemory.platform.pushutil.constants.PushJobStatus;
import com.jvmoutofmemory.platform.pushutil.entity.PushJob;

import javax.sql.DataSource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author adam
 * @date 2021-11-17
 */
public class PushJobDao extends BaseDao {

    public static final String TABLE_NAME = "push_job";

    /**
     * 所有列
     */
    private static final String ALL_COLUMNS = " id,url,param,param_type,method,status,times,max_retry,msg,create_time,update_time,request_id,sys_type,listener,call_back_param,call_back_type,call_back_status,call_back_times,push_rid,external_info";
    /**
     * 不含clob列
     */
    private static final String LIGHT_COLUMNS = " id,url,param_type,method,status,times,max_retry,create_time,update_time,request_id,sys_type,listener,call_back_type,call_back_status,call_back_times,push_rid ";

    public PushJobDao(DataSource dataSource) {
        super(dataSource);
    }

    /**
     * 查询N天前的 推送成功的数据
     * @param days
     * @return
     */
    public List<Long> selectFinishData(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -days);
        Date endDate = calendar.getTime();

        String sql = "select id from push_job where status = 2 and create_time <= ?";
        List<Long> ids = jdbcTemplate.queryForList(sql, Long.class, endDate);
        return ids;
    }

    /**
     * 选择从未被推送过的数据
     * @param size
     * @return
     */
    public List<PushJob> selectNotPushed(int size) {
        String sql = "select ".concat(ALL_COLUMNS).concat(" from ").concat(TABLE_NAME)
                .concat(" where status = ? order by create_time asc limit ?");

        return jdbcTemplate.query(sql, new DefaultRowMapper<>(PushJob.class), PushJobStatus.NOT_PUSHED.getCode(), size);
    }

    /**
     * 选择推送失败、但尚未到达最大失败次数的数据
     * @param size
     * @return
     */
    public List<PushJob> selectPushFailed(int size) {
        String sql = "select ".concat(ALL_COLUMNS).concat(" from ").concat(TABLE_NAME)
                .concat(" where status = ? and times < max_retry order by create_time asc limit ?");

        return jdbcTemplate.query(sql, new DefaultRowMapper<>(PushJob.class), PushJobStatus.FAILED.getCode(), size);
    }

    public int deleteById(Long id) {
        String sql = "delete from ".concat(TABLE_NAME).concat(" where id = ?");
        return jdbcTemplate.update(sql, id);
    }

}
